<template>
  <qx-table :option="tableOption" :remoteData="remoteData">
    <template v-if="false" v-slot:top>
      <qx-form v-model="searchForm" :option="tableOption" isSearch @submit="startSearch"></qx-form>
    </template>
    <template v-slot:menuLeft>
      <q-btn color="primary" icon="add" unelevated @click="handleCreate">
        {{ $t('Add') }}
      </q-btn>
      <q-import :errorParam="['RCS_MAP', 'mapPointType']" downUrl="/yfagv/api/mapPointPackageCfg/downloadModel"
        importUrl="/yfagv/api/mapPointPackageCfg/import" @import-after="startSearch"></q-import>
    </template>
    <template v-slot:menuLeftR>
      <q-icon color="warning" name="mdi-map-marker-question cursor-pointer cursor-hover" size="1.5rem">
        <q-tooltip class="q-pa-md" v-bind="$tooltipAttr">{{ $t('Misc.DblClickCardTips') }}</q-tooltip>
      </q-icon>
    </template>
    <template v-slot:positionImageId="{ row }">
      <div class="full-width row justify-center q-mt-xs">
        <q-img v-if="row.positionImageUrl" :src="formatPath(row.positionImageUrl)"
          class="col-6 cursor-pointer cursor-hover-image rounded-borders"
          error-src="src/views/MapCore/MapGlobal/assets/LoadFail.png" fit="contain" height="2.5rem"
          spinner-color="white" spinner-size="2rem" @click="handleInfo(row)"></q-img>
        <div class="text-center q-py-sm full-width">{{ row.positionPackageName }}</div>
        <div class="row full-width text-dark text-weight-medium text-body1">
          <div>{{ row[toI18nName('elementCategoryNameZhCn')] }}</div>
          <q-space></q-space>
          <div>{{ row[toI18nName('categoryDataNameZhCn')] }}</div>
        </div>
      </div>
    </template>
    <template v-slot:menu="{ row }">
      <q-btn class="col-full-width" color="primary" outline unelevated @click="handleUpdateAttrs(row)">
        {{ $t('MapCore.StationAttrsCfg') }}
      </q-btn>
      <template v-if="row.sysInner !== '1'">
        <q-btn class="col" color="primary" icon="mdi-square-edit-outline" outline unelevated @click="handleUpdate(row)">
          {{ $t('Edit') }}
        </q-btn>
        <q-btn class="col" color="primary" icon="delete" outline unelevated @click="handleDelete(row)">
          {{ $t('Del') }}
        </q-btn>
      </template>
    </template>
  </qx-table>
  <q-modal v-model="modalVisible" :header="formInfo.id ? $t('Edit') : $t('Add')" :width="500" btnAlign="center"
    position="right" @beforeClose="beforeClose" @confirm="submitForm">
    <qx-form ref="FormRef" v-model="formInfo" :option="tableOption"></qx-form>
  </q-modal>
  <q-modal v-model="attrsVisible" v-model:loading="loading" :header="header" @beforeClose="beforeClose"
    @confirm="submitAttrs">
    <StationAttrsCfg ref="AttrsRef" v-model="attrsVisible" :rowInfo="rowInfo"></StationAttrsCfg>
  </q-modal>
  <q-modal v-model="infoVisible" :header="`${$t('Misc.SpecifyDetails')}`" :menuBtn="false" :persistent="false"
    width="620">
    <QInfo :columns="tableOption.column || []" :rowInfo="rowInfo" cols="2" headerWidth="100">
      <template v-slot:positionImageId="{ row }">
        <q-img v-if="row.positionImageUrl" :src="formatPath(row.positionImageUrl)" class="rounded-borders"
          error-src="src/views/MapCore/MapGlobal/assets/LoadFail.png" fit="contain" height="2.5rem"
          spinner-color="white" spinner-size="2rem" width="2.5rem"></q-img>
      </template>
    </QInfo>
  </q-modal>
</template>
<script setup>
import { i18n, toI18nName } from 'boot/i18n.js'
import { deleteAPI, postAPI, putAPI } from 'src/api/index.js'
import { getRemoteData, setRemoteData } from 'src/enum/ajaxRemoteData.js'
import { enableOrDisable, yesOrNo } from 'src/enum/index.js'
import StationAttrsCfg from 'src/views/MapCore/StationAttrsCfg.vue'
import { userStores } from 'stores/user-stores.js'
import { computed, onMounted, ref } from 'vue'
import { createDialog, deepClone } from 'src/utils/utils.js'

const header = ref('')
const rowInfo = ref({})
const formInfo = ref({})
const userStore = userStores()
const FormRef = ref(null)
const AttrsRef = ref(null)
const pointTypes = ref([])
const searchForm = ref({})
const loading = ref(false)
const businessKind = ref([])
const businessTypes = ref([])
const infoVisible = ref(false)
const attrsVisible = ref(false)
const modalVisible = ref(false)
const remoteData = ref({ dicUrl: '/yfagv/api/mapPointElementCfg/list' })
getRemoteData('station_type', '/yfagv/api/mapElementType/list').then(data => (pointTypes.value = data))
getRemoteData('station_kind_type', '/yfagv/api/mapPointElementCfg/listElementAllDataInfo').then(data => {
  businessKind.value = data.category
  businessTypes.value = data.categoryData
})
const formatPath = computed(() => path => `${userStore.OSSPath}/${path}`)
const formatBusinessTypes = computed(() => {
  return businessTypes.value.filter(el => el.categoryCode === formInfo.value.positionElementCategoryCode)
})
const tableOption = computed(() => {
  return {
    grid: true, span: 22, labelWidth: 100, searchSpan: 4, headerWidth: 60,
    searchLabelWidth: 60,
    column: [{
      label: `${i18n.t('MapCore.StationType')}`, field: 'positionTypeCode', type: 'select', options: pointTypes.value,
      props: { label: toI18nName('elementTypeNameZhCn'), value: 'elementTypeCode' }, minWidth: 80,
      topLeft: true
    }, {
      label: `${i18n.t('MapCore.StationName')}`, field: 'positionPackageName', minWidth: 80, hide: true
    }, {
      label: i18n.t('MapCore.StationThumbnail'), field: 'positionImageId', type: 'picture', minWidth: 80,
      required: true, limitNum: 1, sName: 'MapMaking', bName: 'MapPoint', publicRead: true,
      slot: true, format: (_, row) => row.positionImageUrl, nonHeader: true, search: false,
      change: (_, imgs = []) => {
        (imgs)
        formInfo.value.positionImageUrl = imgs[0]?.resultPath || ''
      }
    }, {
      label: `${i18n.t('MapCore.MainCategory')}`, field: 'positionElementCategoryCode', type: 'select',
      options: businessKind.value, minWidth: 100, required: true, value: businessKind.value[0]?.elementCategoryCode,
      props: { label: toI18nName('elementCategoryNameZhCn'), value: 'elementCategoryCode' },
      format: (_, row) => row[toI18nName('elementCategoryNameZhCn')], hide: true
    }, {
      label: `${i18n.t('MapCore.SubCategory')}`, field: 'positionElementCategoryInfoCode', type: 'select',
      options: formatBusinessTypes.value, minWidth: 100, display: !!formatBusinessTypes.value.length,
      props: { label: toI18nName('categoryDataNameZhCn'), value: 'categoryDataCode' },
      format: (_, row) => row[toI18nName('categoryDataNameZhCn')], hide: true, search: false
    }, {
      label: `${i18n.t('Sorting')}`, field: 'sortId', type: 'number', min: 0, decimals: 0, minWidth: 60,
      search: false, hide: true
    }, {
      label: `${i18n.t('BuiltIn')}`, field: 'sysInner', search: false, display: false, options: yesOrNo.value,
      useTag: true, minWidth: 80, hide: true
    }, {
      label: `${i18n.t('IsEnable')}`, field: 'isEnable', type: 'radio', searchType: 'select', value: '1',
      options: enableOrDisable.value, useTag: true, topRight: true
    }, {
      label: `${i18n.t('CreationTime')}`, field: 'createdTime', display: false, minWidth: 80, search: false, hide: true
    }]
  }
})

const handleCreate = () => {
  modalVisible.value = true
}
const handleInfo = row => {
  rowInfo.value = row
  infoVisible.value = true
}
const handleUpdateAttrs = (row = {}) => {
  loading.value = true
  attrsVisible.value = true
  header.value = `${i18n.t('MapCore.StationAttrsCfg')}(${row.positionPackageName || ''})`
  postAPI('/yfagv/api/agvMapPointAttributeValue/getAttributeValueByCode', row, data => {
    rowInfo.value = data
    loading.value = false
  }, () => loading.value = false)
}
const handleUpdate = row => {
  formInfo.value = deepClone(row)
  modalVisible.value = true
}
const handleDelete = row => {
  createDialog({ msg: `${i18n.t('DelTips')}` }, () => {
    deleteAPI(`/yfagv/api/mapPointElementCfg/${row.id}`, {}, () => startSearch('clear'))
  }, () => { })
}
const formatSearchForm = () => ({ ...searchForm.value })
const startSearch = (action, done) => {
  remoteData.value.params = formatSearchForm()
  remoteData.value.clearSelected = true
  if (done) done()
  action === 'clear' && setRemoteData('station_package_type')
}
const beforeClose = () => {
  if (FormRef.value) FormRef.value.onReset()
  attrsVisible.value = false
  modalVisible.value = false
}
const submitAttrs = mDone => AttrsRef.value && AttrsRef.value.submitAjax(mDone)
const submitForm = mDone => {
  FormRef.value.validate((form, done) => {
    const API = form.id ? putAPI : postAPI
    API('/yfagv/api/mapPointElementCfg', form, () => {
      startSearch('clear')
      done()
      mDone && mDone()
    }, () => {
      done()
      mDone && mDone(false)
    })
  }, () => mDone && mDone(false))
}
onMounted(startSearch)
</script>